﻿using System;
using System.ComponentModel.Composition;
using System.Web.Mvc;
using PAMD.Business.Models;
using PAMD.Database;
using PAMD.Database.Services;
using PAMD.Controllers.Extension;

namespace PAMD.Controllers.Account
{
    [Export]
    [PartCreationPolicy(CreationPolicy.NonShared)]
    public class RegisterController : Controller
    {
        [Import(typeof(AccountService))]
        private AccountService RegService { get; set; }

        [Import(typeof(CommonService))]
        private CommonService CommonService { get; set; }

        public ActionResult Index(RegistrationModel registration)
        {
            if (registration.Countries == null)
            {
                registration.Countries = CommonService.GetCountryList().ToSelectListItems();
            }
            return View(registration);
        }

        public ActionResult Complete(RegistrationModel registration)
        {
            if (registration.Countries == null)
            {
                registration.Countries = CommonService.GetCountryList().ToSelectListItems();
            }

            if (registration.Email.Length > 5)
            {
                bool isUserRegistered = RegService.IsUserRegistered(registration.Email);

                if (!isUserRegistered)
                {
                    Registration reg = new Registration
                                           {
                                               FirstName = registration.FirstName,
                                               LastName = registration.LastName,
                                               Email = registration.Email,
                                               Password = registration.Password,
                                               Country = registration.Country
                                           };
                    string host = HttpContext.Request.Url.GetLeftPart(UriPartial.Authority);
                    RegService.AddRegistration(reg, host);
                    return View(registration);
                }

                ModelState.AddModelError(string.Empty,"User already registered.");
                return View("Index", registration);
            }

            ModelState.AddModelError(string.Empty, "Email address not valid.");
            return View("Index", registration);
        }
    }
}
